﻿using NewRen.Helpers;
using NewRen.Log4net;
using NewRen.Models;
using NewRen.Models.DataModel;
using NewRen.Models.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace NewRen.Controllers
{
    public class ShopController : BaseController
    {
        public ActionResult Index(string type)
        {
            try
            {
                ViewBag.Type = (type == null ? "" : type);
                var types = db.ProductTypes.DistinctBy(p => p.TypeName).Take(8).ToList();
                ViewBag.types = types;
                return View();
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("积分商城出错", HttpHelper.GetIPAddress()), ex);
                return Redirect("/Shared/Info?msg=数据异常，请稍后重试");
            }
        }

        public ActionResult getProducts(int page, string type)
        {
            int index = page * 12;
            AjaxModel ajaxModel = new AjaxModel();
            List<vProductList> vlist = new List<vProductList>();
            try
            {
                IEnumerable<Product> query = db.Products.AsEnumerable();
                if (!string.IsNullOrEmpty(type))
                {
                    query = query.Where(p => p.ProductType == type);
                }
                var plist = query.Skip(index).Take(12).ToList();
                if (plist.Count <= 0)
                {
                    ajaxModel.Statu = "end";
                    ajaxModel.Msg = "没有更多数据！";
                }
                else
                {
                    foreach (var item in plist)
                    {
                        vlist.Add(new vProductList(item));
                    }
                    ajaxModel.Data = vlist;
                    ajaxModel.Statu = "ok";
                }
            }
            catch(Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "数据异常";
                log.Error(new LogContent("积分商城获取产品加载出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }
    }
}
